import React, { Component } from 'react'
import NenmoConCointract from '../build/contracts/NenmoCoin.json'
import getWeb3 from './utils/getWeb3'

import './css/oswald.css'
import './css/open-sans.css'
import './css/pure-min.css'
import './App.css'

class App extends Component {
  constructor(props) {
    super(props)

    this.state = {
      storageValue: 0,
      web3: null,
      instance:null,
      accounts:null,
    }
  }

  componentWillMount() {
    // Get network provider and web3 instance.
    // See utils/getWeb3 for more info.

    getWeb3
    .then(results => {
      this.setState({
        web3: results.web3
      })

      // Instantiate contract once web3 provided.
      this.instantiateContract()
    })
    .catch(() => {
      console.log('Error finding web3.')
    })
  }

  sell(){
    let amount = this.refs.amount.value;
    let account = this.refs.account.value;
    console.log('amount',amount);
    console.log('account',account);
    if(!amount){
      alert("请填写转账金额！");
      return;
    }
    if(!account){
      alert("请填写转账账户！");
      return;
    }
    //开始转账
    if(!this.state.instance){
      alert('合约未初始化！');
    }else{
      let nenMoInstance = this.state.instance;
      nenMoInstance.transfer(this.state.accounts[1],amount,{from:this.state.accounts[0]});
      nenMoInstance.balanceOf(this.state.accounts[0]).then((res)=>{
        let amount = res.toNumber();
        this.setState({totalSupply:amount});
      });
    }
  }

  instantiateContract() {
    console.log('instantiateContract start!');
    /*
     * SMART CONTRACT EXAMPLE
     *
     * Normally these functions would be called in the context of a
     * state management library, but for convenience I've placed them here.
     */

    const contract = require('truffle-contract');
    const nenMoCoin = contract(NenmoConCointract);
    nenMoCoin.setProvider(this.state.web3.currentProvider)

    // Declaring this for later so we can chain functions on SimpleStorage.
    var nenMoInstance;

    // Get accounts.
    this.state.web3.eth.getAccounts((error, accounts) => {
      this.setState({accounts:accounts});
      nenMoCoin.deployed(210000).then((instance) => {
        this.setState({instance:instance});
        nenMoInstance = instance;
        console.log('accounts[0]',accounts[0]);
        return nenMoInstance.balanceOf(accounts[0]);
      }).then(amountOfOwner=>{
        let amount = amountOfOwner.toNumber();
        this.setState({totalSupply:amount});
      });
    })
  }

  render() {
    return (
      <div className="App">
        <nav className="navbar pure-menu pure-menu-horizontal">
            <a href="#" className="pure-menu-heading pure-menu-link">Truffle Box</a>
        </nav>

        <main className="container">
          <div className="pure-g">
            <div className="pure-u-1-1">
              <h1>Good to Go!</h1>
              <p>Your Truffle Box is installed and ready.</p>
              <h2>Coin Smart Contract Example</h2>
              <p>If your contracts compiled and migrated successfully, below will show a stored value of 210000 (by default).</p>
              <p>The stored value is: {this.state.totalSupply}</p>
              <p>金额: <input ref="amount" type="text" placeholder="转账金额"/></p>
              <p>交易账户:<input ref="account" type="text" placeholder="交易账户"/></p>
              <p><button onClick={this.sell.bind(this)}>
                出售
              </button></p>
            </div>
          </div>
        </main>
      </div>
    );
  }
}

export default App
